<template>
  <div class="new_order">
    <el-card class="box-card ">
      <div slot="header" class="clearfix">
        <span class="clearfixText"><i class="el-icon-s-order" />创建订单</span>
        <el-button size="mini" type="primary" plain class="right_btn" @click="historyBtn">历史订单</el-button>
      </div>
      <el-form
        ref="newOrderFormRef"
        :inline="true"
        :model="newOrderForm"
        :rules="newOrderRules"
        class="demo-form-inline"
      >
        <el-collapse v-model="activeNames">
          <el-collapse-item title="装卸信息" name="1">
            <div class="el-collapse-item_form_items">
              <el-form-item label="装货单位" prop="loadCompany">
                <!-- <el-input v-model="newOrderForm.loadCompany" size="small" placeholder="请输入" /> -->
                <el-autocomplete
                  v-model="newOrderForm.loadCompany"
                  class="inline-input"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleLoadSelect"
                />
              </el-form-item>
              <el-form-item label="装货联系人" prop="loadName">
                <el-input v-model="newOrderForm.loadName" size="small" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="装货电话" prop="loadPhone">
                <el-input v-model="newOrderForm.loadPhone" size="small" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="装货日期" prop="planLoadDate">
                <el-date-picker
                  v-model="newOrderForm.planLoadDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              <el-form-item label="时间" prop="planLoadTimePeriod">
                <el-select v-model="newOrderForm.planLoadTimePeriod" placeholder="请选择">
                  <el-option
                    v-for="item in dateSectorList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="el-collapse-item_form_items">
              <ProvincesSelect ref="loadProvinces" :province-value="[newOrderForm.loadProvince,newOrderForm.loadProvinceCode]" :city-value="[newOrderForm.loadCity,newOrderForm.loadCityCode]" :district-value="[newOrderForm.loadDistrict,newOrderForm.loadDistrictCode]" :weight="700" :color="'#606266'" @backAddress="backLoadAddress">
                <template #title><i>*</i> 装货省市区 </template>
              </ProvincesSelect>
              <el-form-item label="装货详细地址" class="siteInput" prop="loadAddress">
                <el-input v-model="newOrderForm.loadAddress" size="small" placeholder="输入详细地址可只能识别省市区" />
              </el-form-item>
            </div>
            <div class="el-collapse-item_form_items">
              <el-form-item label="卸货单位" prop="unloadCompany">
                <el-autocomplete
                  v-model="newOrderForm.unloadCompany"
                  class="inline-input"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleUnloadSelect"
                />
              </el-form-item>
              <el-form-item label="卸货联系人" prop="unloadName">
                <el-input v-model="newOrderForm.unloadName" size="small" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="卸货电话" prop="unloadPhone">
                <el-input v-model="newOrderForm.unloadPhone" size="small" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="卸货日期" prop="planUnloadDate">
                <el-date-picker
                  v-model="newOrderForm.planUnloadDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              <el-form-item label="时间" prop="planUnloadTimePeriod">
                <el-select v-model="newOrderForm.planUnloadTimePeriod" placeholder="请选择">
                  <el-option
                    v-for="item in dateSectorList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="el-collapse-item_form_items">
              <ProvincesSelect ref="unloadProvinces" :province-value="[newOrderForm.unloadProvince,newOrderForm.unloadProvinceCode]" :city-value="[newOrderForm.unloadCity,newOrderForm.unloadCityCode]" :district-value="[newOrderForm.unloadDistrict,newOrderForm.unloadDistrictCode]" :disabled="addresDisabled" :weight="700" :color="'#606266'" @backAddress="backUnloadAddress">
                <template #title><i>*</i> 卸货省市区 </template>
              </ProvincesSelect>
              <el-form-item label="卸货详细地址" class="siteInput" prop="unloadAddress">
                <el-input v-model="newOrderForm.unloadAddress" :disabled="addresDisabled" size="small" placeholder="输入详细地址可只能识别省市区" />
              </el-form-item>

            </div>
            <div class="el-collapse-item_form_checkbox">
              <el-form-item>
                <el-checkbox v-model="newOrderForm.needSave">存为常用联系人</el-checkbox>
              </el-form-item>
            </div>
          </el-collapse-item>
          <el-collapse-item title="还柜信息" name="2">
            <div class="el-collapse-item_form_items">
              <el-form-item label="还柜联系人" prop="cabinetName">
                <el-input v-model="newOrderForm.cabinetName" size="small" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="还柜电话" prop="cabinetPhone">
                <el-input v-model="newOrderForm.cabinetPhone" size="small" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="还柜地" class="siteInput" prop="cabinetAddress">
                <el-input v-model="newOrderForm.cabinetAddress" size="small" placeholder="详细地址" />
              </el-form-item>
            </div>
          </el-collapse-item>
          <el-collapse-item title="货物信息" name="3" class="table_collapse-item">
            <table border="1" cellspacing="0" cellpadding="5" borderColor="#ccc">
              <tr class="table_header">
                <td><i>*</i>货物名称</td>
                <td><i>*</i>货物类型</td>
                <td><i>*</i>重量（吨）</td>
                <td>体积（m²）</td>
                <td>数量</td>
                <td>单位</td>
              </tr>
              <tr class="table_body" style="height:80px">
                <td>
                  <el-form-item prop="goodsName">
                    <el-autocomplete
                      v-model="newOrderForm.goodsName"
                      class="inline-input"
                      :fetch-suggestions="queryGoodsNameSearch"
                      placeholder="请输入内容"
                      @select="handleGoodsNameSelect"
                    />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item prop="goodsType">
                    <el-select v-model="newOrderForm.goodsType" placeholder="请选择" @blur="manualVerify">
                      <el-option
                        v-for="item in goodsTypeSelectList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.name"
                      />
                    </el-select>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item prop="totalWeight">
                    <el-input
                      v-model="newOrderForm.totalWeight"
                      oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                      size="small"
                      placeholder="0.00"
                      @blur="totalWeightValueFixed"
                    />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item prop="volume">
                    <el-input
                      v-model="newOrderForm.volume"
                      size="small"
                      placeholder="0.00"
                      oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                      @blur="volumeValueFixed"
                    />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item prop="goodsAmount">
                    <el-input v-model="newOrderForm.goodsAmount" size="small" placeholder="" oninput="value=value.replace(/[^\d]/g,'')" />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item prop="goodsUnit">
                    <el-select v-model="newOrderForm.goodsUnit" placeholder="请选择">
                      <el-option
                        v-for="item in unitsTypeSelectList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                      />
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
            </table>
          </el-collapse-item>
          <el-collapse-item title="备注信息" name="4" class="collapse_remarks">
            <el-form-item prop="remake">
              <el-input
                v-model="newOrderForm.remake"
                type="textarea"
                :rows="5"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </el-card>
    <div class="hurdleBtn">
      <el-button @click="orderAdd(false)">保存</el-button>
      <el-button type="primary" @click="orderAdd(true)">保存并派单</el-button>
    </div>
    <el-dialog title="请选择历史订单" :visible.sync="historyVisible">
      <div>
        <el-form :inline="true" :model="historyOrderForm" class="demo-form-inline">
          <el-form-item label="装货单位">
            <el-input v-model="historyOrderForm.loadCompany" placeholder="装货单位" />
          </el-form-item>
          <el-form-item label="卸货单位">
            <el-input v-model="historyOrderForm.unloadCompany" placeholder="卸货单位" />
          </el-form-item>
          <el-form-item label="货物">
            <el-input v-model="historyOrderForm.goodsName" placeholder="货物" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getHistoryList()">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="historyOrderData">
        <el-table-column width="50">
          <template slot-scope="{row}">
            <el-button type="text" @click="selectHistoryOrder(row)">选择</el-button>
          </template>
        </el-table-column>
        <el-table-column property="loadCompany" label="装货单位" />
        <el-table-column label="装货地">
          <template slot-scope="{row}">
            {{ row.loadProvince }}-{{ row.loadCity }}-{{ row.loadDistrict }}-{{ row.loadAddress }}
          </template>
        </el-table-column>
        <el-table-column property="unloadCompany" label="卸货单位" />
        <el-table-column label="卸货地">
          <template slot-scope="{row}">
            {{ row.unloadProvince }}-{{ row.unloadCity }}-{{ row.unloadDistrict }}-{{ row.unloadAddress }}
          </template>
        </el-table-column>
        <el-table-column property="goodsName" label="货物" />
        <el-table-column property="goodsType" label="货物类型" />
        <el-table-column property="originTotalWeight" label="重量" width="70" />
        <el-table-column property="loadName" label="装货联系人" />
        <el-table-column property="loadPhone" label="装货电话" />
        <el-table-column property="unloadName" label="卸货联系人" />
        <el-table-column property="unloadPhone" label="卸货电话" />
      </el-table>
      <div class="pagination">
        <el-pagination
          :current-page="historyPager.current"
          :page-sizes="historyPager.sizes"
          :page-size="historyPager.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="historyPager.total"
          @size-change="changeTableSize"
          @current-change="changeTableCurrent"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postOrderAdd, getGoodsTypeList, unitsTypeList, goodsNameList, getHistoryOrderList, postUpdateOrder } from '@/api/tms/order'
import { getContantList } from '@/api/tms/contact'
import ProvincesSelect from '@/components/ProvincesSelect'
export default {
  components: {
    ProvincesSelect
  },
  data() {
    return {
      restaurants: [],
      state1: '',
      activeNames: ['1'],
      addresDisabled: false,
      // 创建订单表单
      newOrderForm: {
        loadCompany: '',
        loadName: '',
        loadPhone: '',
        loadProvince: '',
        loadProvinceCode: '',
        loadCity: '',
        loadCityCode: '',
        loadDistrict: '',
        loadDistrictCode: '',
        loadAddress: '',
        planLoadDate: '',
        planLoadTimePeriod: '',
        unloadCompany: '',
        unloadName: '',
        unloadPhone: '',
        unloadProvince: '',
        unloadProvinceCode: '',
        unloadCity: '',
        unloadCityCode: '',
        unloadDistrict: '',
        unloadDistrictCode: '',
        unloadAddress: '',
        planUnloadDate: '',
        planUnloadTimePeriod: '',
        cabinetName: '',
        cabinetPhone: '',
        cabinetProvince: '',
        cabinetProvinceCode: '',
        cabinetCity: '',
        cabinetCityCode: '',
        cabinetDistrict: '',
        cabinetDistrictCode: '',
        cabinetAddress: '',
        remake: '',
        goodsName: '',
        goodsType: '',
        totalWeight: '',
        volume: '',
        goodsAmount: '',
        goodsUnit: '',
        needSave: false,
        createFrom: 'TMS',
        orderType: 'BULK_CARGO'
      },
      dateSectorList: [{
        value: '0:00-6:00',
        label: '0:00-6:00'
      }, {
        value: '6:00-12:00',
        label: '6:00-12:00'
      }, {
        value: '12:00-18:00',
        label: '12:00-18:00'
      }, {
        value: '18:00-24:00',
        label: '18:00-24:00'
      }],
      // 弹窗表单
      historyOrderForm: {
        goodsName: '',
        loadCompany: '',
        unloadCompany: ''
      },
      // 历史订单列表
      historyOrderData: [],
      // 表单校验
      newOrderRules: {
        // loadCompany: [
        //   { min: 0, max: 50, message: '不得超过50个字符', trigger: 'blur' }
        // ],
        loadName: [
          { required: true, message: '请输入装货联系人', trigger: 'blur' },
          { min: 0, max: 20, message: '不得超过20个字符', trigger: 'blur' }
        ],
        loadPhone: [
          { required: true, message: '请输入装货电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        loadAddress: [
          { required: true, message: '请装货输入详细地址', trigger: 'blur' },
          { min: 0, max: 100, message: '不得超过100个字符', trigger: 'blur' }
        ],
        unloadName: [
          { required: true, message: '请输入卸货货联系人', trigger: 'blur' }
        ],
        unloadPhone: [
          { required: true, message: '请输入卸货电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        unloadAddress: [
          { required: true, message: '请输入卸货详细地址', trigger: 'blur' },
          { min: 0, max: 100, message: '不得超过100个字符', trigger: 'blur' }
        ],
        goodsName: [
          { required: true, message: '请输入货物名称', trigger: ['blur', 'change'] }
        ],
        goodsType: [
          { required: true, message: '请输入货物名称', trigger: 'change' }
        ],
        totalWeight: [
          { required: true, message: '请填写重量', trigger: 'blur' }
        ]
      },
      // 货物类型列表
      goodsTypeSelectList: [],
      // 单位类型列表
      unitsTypeSelectList: [],
      // 历史分页
      historyPager: {
        total: 0,
        sizes: [10, 20, 30],
        size: 10,
        current: 1
      },
      historyVisible: false
    }
  },
  created() {
    if (this.$route.path.indexOf('revampOrder') !== -1) {
      const row = this.$route.query.row
      if (row.status === 'PROCESSING') {
        this.addresDisabled = true
      }
      for (const key in row) {
        if (key === 'originTotalWeight') {
          this.newOrderForm.totalWeight = row[key].toFixed(2)
        } else {
          this.newOrderForm[key] = row[key]
        }
      }
    }
  },
  async mounted() {
    this.goodsTypeSelectList = await getGoodsTypeList()
    this.unitsTypeSelectList = await unitsTypeList()
  },
  methods: {
    totalWeightValueFixed() {
      if (this.newOrderForm.totalWeight !== '' && this.newOrderForm.totalWeight !== '0' && this.newOrderForm.totalWeight !== '0.00') {
        this.newOrderForm.totalWeight = Number(this.newOrderForm.totalWeight).toFixed(2)
      } else {
        this.newOrderForm.totalWeight = ''
      }
    },
    volumeValueFixed() {
      if (this.newOrderForm.volume !== '') {
        this.newOrderForm.volume = Number(this.newOrderForm.volume).toFixed(2)
      }
    },
    manualVerify() {
      console.log(this.$refs.newOrderFormRef.validateField('goodsType'))
      this.$refs.newOrderFormRef.validateField('goodsType')
    },
    // 装货省市区下拉选择框封装回调
    backLoadAddress(obj) {
      for (const key in obj) {
        if (obj[key] instanceof Array && obj[key].length !== 0) {
          this.newOrderForm[`load${key}`] = obj[key][0]
          this.newOrderForm[`load${key}Code`] = obj[key][1]
        }
      }
    },
    // 卸货省市区下拉选择封装回调
    backUnloadAddress(obj) {
      for (const key in obj) {
        if (obj[key] instanceof Array && obj[key].length !== 0) {
          this.newOrderForm[`unload${key}`] = obj[key][0]
          this.newOrderForm[`unload${key}Code`] = obj[key][1]
        }
      }
    },
    // 根据装货单位模糊搜索
    async querySearch(queryString, cb) {
      var res = await getContantList({ unit: queryString })
      if (res.length !== 0) {
        res.forEach(item => {
          item.value = item.unit
        })
      }
      // 调用 callback 返回建议列表的数据
      cb(res)
    },
    // 根据货物名称进行模糊搜索
    async queryGoodsNameSearch(queryString, cb) {
      var res = await goodsNameList({ name: queryString })
      if (res.length !== 0) {
        res.forEach(item => {
          item.value = item.name
        })
      }
      cb(res)
    },
    // 装货单位选择模糊搜索列表之后的回调
    handleLoadSelect(item) {
      this.newOrderForm.loadName = item.name
      this.newOrderForm.loadPhone = item.mobile
      this.newOrderForm.loadProvince = item.province
      this.newOrderForm.loadCity = item.city
      this.newOrderForm.loadDistrict = item.district
      this.newOrderForm.loadAddress = item.address
      this.newOrderForm.loadProvinceCode = item.provinceCode
      this.newOrderForm.loadCityCode = item.cityCode
      this.newOrderForm.loadDistrictCode = item.districtCode
    },
    // 卸货单位选择模糊搜索列表之后的回调
    handleUnloadSelect(item) {
      this.newOrderForm.unloadName = item.name
      this.newOrderForm.unloadPhone = item.mobile
      this.newOrderForm.unloadProvince = item.province
      this.newOrderForm.unloadCity = item.city
      this.newOrderForm.unloadDistrict = item.district
      this.newOrderForm.unloadAddress = item.address
      this.newOrderForm.unloadProvinceCode = item.provinceCode
      this.newOrderForm.unloadCityCode = item.cityCode
      this.newOrderForm.unloadDistrictCode = item.districtCode
    },
    // 货物名称选择模糊搜索列表之后的回调
    handleGoodsNameSelect(item) {
      this.newOrderForm.goodsName = item.name
      this.newOrderForm.goodsType = item.typeName
      this.newOrderForm.totalWeight = Number(item.weight).toFixed(2)
      this.newOrderForm.volume = Number(item.volume).toFixed(2)
      this.newOrderForm.goodsAmount = item.quantity
      this.newOrderForm.goodsUnit = item.unitName
    },
    // 调用新增订单接口
    orderAdd(routerGo) {
      if (this.newOrderForm.loadCompany.length >= 50) return this.$message.warning('请输入正确的装货单位')
      if (this.newOrderForm.unloadCompany.length >= 50) return this.$message.warning('请输入正确的卸货单位')
      this.$refs.newOrderFormRef.validate(async(valid) => {
        const bool = this.$refs.loadProvinces.rulesVerify() && this.$refs.unloadProvinces.rulesVerify()
        if (valid && bool) {
          const data = this.newOrderForm
          try {
            if (this.$route.name === 'revampOrder') {
              const { orderNo } = await postUpdateOrder({ ...data, orderNo: this.$route.query.row.orderNo })
              if (routerGo) {
                this.$router.push({ path: '/orderManage/deliveryList', query: { id: orderNo }})
              } else {
                this.$message.success('操作成功')
              }
            } else {
              const { orderNo } = await postOrderAdd(data)
              if (routerGo) {
                this.$router.push({ path: '/orderManage/deliveryList', query: { id: orderNo }})
              } else {
                this.$message.success('操作成功')
              }
            }
          } catch {
            return
          }
        } else {
          this.$message.warning('请填写必填项')
          return false
        }
      })
    },
    // 点击历史订单搜索历史订单
    async historyBtn() {
      await this.getHistoryList()
      this.historyVisible = true
    },
    async getHistoryList() {
      const historyPager = {
        current: this.historyPager.current,
        size: this.historyPager.size
      }
      console.log(this.historyOrderForm)
      const { records, total } = await getHistoryOrderList({ ...historyPager, ...this.historyOrderForm })
      this.historyPager.total = total
      this.historyOrderData = records
    },
    // 历史订单分页
    changeTableCurrent(val) {
      this.historyPager.current = val
      this.getHistoryList()
    },
    changeTableSize(val) {
      this.historyPager.size = val
      this.historyPager.current = 1
      this.getHistoryList()
    },
    selectHistoryOrder(row) {
      for (const key in row) {
        if (key === 'originTotalWeight') {
          this.newOrderForm.totalWeight = row[key].toFixed(2)
        } else {
          this.newOrderForm[key] = row[key]
        }
      }
      this.historyVisible = false
    }
  }
}

</script>

<style lang='scss'>
.new_order {
  width: 100%;
  padding-bottom: 30px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }
  // 卡片样式
  .box-card {
    width: 95%;
    margin-top: 20px;

  }
  // 折叠表样式
  .el-collapse{
    .el-collapse-item__header{
      background-color: #e5eff9;
      border: 1px solid #ccc;
      padding: 8px 10px;
      border-left: 4px solid #1e90ff;
      font-weight: 700;
    }
    .el-collapse-item__wrap{
      border-bottom: 0;
      .el-collapse-item__content{
        padding: 0;
        .el-collapse-item_form_items{
          height: 80px;
          border: 1px solid #ccc;
          display: flex;
          justify-content: space-around;
          align-items: center;
          .el-form-item{
            margin: 0;
          }
          .siteInput{
            .el-form-item__content{
              width: 575px;
            }
          }
        }
        .el-collapse-item_form_checkbox{
          .el-form-item{
            margin: 0;
          }
        }
      }
    }
    .table_collapse-item{
      .el-collapse-item__wrap{
        border-right: 1px solid #d0d0d0;
      }
    }
    .collapse_remarks{
      .el-collapse-item__wrap{
        border: 1px solid #d0d0d0;
        .el-form-item {
          margin: 0;
          margin: 10px 10px 20px 10px;
          width: 98%;
          .el-form-item__content{
            width: 100%;
          }
        }
        textarea{
          border: 1px solid #a5a5a5;
        }
      }
    }
  }
  .hurdleBtn{
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }
  //弹窗样式修改
  .el-dialog__wrapper{
    margin-bottom: 20px;
    .el-dialog{
      width: 85%;
      .el-dialog__header{
        span{
          font-weight: 700;
        }
      }
    }
  }
}
</style>

